Source code for hysop.tools.contexts

# Copyright (c) HySoP 2011-2024
#
# This file is part of HySoP software.
# See "https://particle_methods.gricad-pages.univ-grenoble-alpes.fr/hysop-doc/"
# for further info.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import os, time, sys
import numpy as np
from contextlib import contextmanager, ExitStack


[docs] @contextmanager def nested(*managers): with ExitStack() as stack: yield tuple(stack.enter_context(m) for m in managers)
[docs] class Timer: def __enter__(self, factor=1): self.start = time.time() self.factor = factor self.end = None self.interval = None return self def __exit__(self, exc_type, exc_val, exc_tb): self.end = time.time() self.interval = (self.end - self.start) * self.factor if exc_type: raise
[docs] @contextmanager def printoptions(*args, **kwargs): original = np.get_printoptions() np.set_printoptions(*args, **kwargs) yield np.set_printoptions(**original)
[docs] @contextmanager def systrace(fn=None): __old_trace = sys.gettrace() def __trace(frame, event, arg): print(f"{event} {frame.f_code.co_filename}:{frame.f_lineno}") fn = fn or __trace sys.settrace(fn) yield sys.settrace(__old_trace)
[docs] @contextmanager def redirect_stdout(fileobj): old = sys.stdout old.flush() sys.stdout = fileobj try: yield fileobj finally: sys.stdout = old
[docs] @contextmanager def redirect_stderr(fileobj): old = sys.stderr old.flush() sys.stderr = fileobj try: yield fileobj finally: sys.stderr = old
# See https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python/22434262#22434262
[docs] @contextmanager def stdout_redirected(to=os.devnull): # C-level redirection (file descriptor level) def fileno(file_or_fd): fd = getattr(file_or_fd, "fileno", lambda: file_or_fd)() if not isinstance(fd, int): raise ValueError("Expected a file (`.fileno()`) or a file descriptor") return fd stdout = sys.stdout stdout_fd = fileno(stdout) with os.fdopen(os.dup(stdout_fd), "wb") as copied: stdout.flush() os.dup2(fileno(to), stdout_fd) try: yield finally: stdout.flush() os.dup2(copied.fileno(), stdout_fd)
[docs] @contextmanager def stderr_redirected(to=os.devnull): # C-level redirection (file descriptor level) def fileno(file_or_fd): fd = getattr(file_or_fd, "fileno", lambda: file_or_fd)() if not isinstance(fd, int): raise ValueError("Expected a file (`.fileno()`) or a file descriptor") return fd stderr = sys.stderr stderr_fd = fileno(stderr) with os.fdopen(os.dup(stderr_fd), "wb") as copied: stderr.flush() os.dup2(fileno(to), stderr_fd) try: yield finally: stderr.flush() os.dup2(copied.fileno(), stderr_fd)